﻿using NewLife.Http;
using NewLife.Reflection;
using NewLife.Remoting;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ZYing.QPanel.Http
{
    public class AsyncControllerHandler<TController> : AsyncHttpHandler
    {
        #region 属性
        /// <summary>控制器类型</summary>
        public Type ControllerType { get; private set; }
        #endregion
        public AsyncControllerHandler(Func<TController> controlFactory)
        {
            this.ControllerType = typeof(TController);
            this.ControllerFactory = controlFactory ?? throw new ArgumentNullException(nameof(controlFactory));
        }
        public Func<TController> ControllerFactory { get; }
        protected override async Task ProcessRequestAsync(IHttpContext context)
        {
            var ss = context.Path.Split('/');
            var methodName = ss.Length >= 3 ? ss[2] : null;

            var controller = this.ControllerFactory.Invoke();

            var method = methodName == null ? null : ControllerType.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (method == null) throw new ApiException(404, $"控制器[{ControllerType.FullName}]内无法找到操作[{methodName}]");

            var result = controller.InvokeWithParams(method, context.Parameters as IDictionary);
            if (result is Task task)
            {
                await task;
                if (method.ReturnType == typeof(Task))
                {
                    context.Response.SetResult(null);
                }
                else
                {
                    dynamic d = task;
                    context.Response.SetResult(d.Result);
                }
            }
            else
            {
                context.Response.SetResult(result);
            }
        }
    }
}
